import React, { Component } from 'react'
import { Carousel, Descriptions, Divider, Image, Layout, List, message, Spin } from 'antd'
import RecommendedReq from '../../components/RecommendedReq'
import ArticleType from '../../types/ArticleType'
import { RouteComponentProps } from 'react-router-dom'
import './deviceDisplay.less'
import '../../views/IndexPage/IndexPage.less'
import Device from '../../types/Device'
import {
    queryAttachment,
    queryCategory,
    queryDeviceInfo,
    queryDevicePictures,
    queryDeviceStereoPicture
} from '../../requests/Device'
import moment from 'moment'
import { devRes, getRes, prodRes } from '../../configFile'
import DataType from '../../types/DataType'
import Axios from 'axios'
import DeviceData from '../../types/DeviceData'
import LineChart from '../../components/2DCharts'
import PictureInfo from '../../types/PictureInfo'
import AttachmentInfo from '../../types/AttachmentInfo'
import ThreeDDisplay from '../../components/3DDisplay'

//具体参数接口
interface DataParam {
    cateName: string
    value: string
    dataType: DataType
}

interface IProps extends RouteComponentProps<{ id: string }> {
}

interface IState {
    attachments: AttachmentInfo[]
    isLoading: boolean
    deviceID: number
    deviceInfo: Device | undefined
    // pictureUrls:Array<string>
    pictureUrls: Array<PictureInfo>
    deviceData: Array<DataParam>
    threeDPaths: string[]
}

export default class DeviceDisplay extends Component<IProps, IState> {
    constructor(props: IProps) {
        super(props)
        this.state = {
            attachments: [],
            isLoading: false,
            deviceID: Number.parseInt(this.props.match.params.id),
            deviceInfo: undefined,
            pictureUrls: [],
            deviceData: [],
            threeDPaths: []
        }
    }

    async componentDidMount() {
        try {
            //获取设备信息
            const deviceInfo = getRes(await queryDeviceInfo(this.state.deviceID))
            if (deviceInfo.isSuccessful) {
                console.log('获取设备信息成功')
                this.setState({
                    deviceInfo: deviceInfo.data.device,
                })
            } else {
                console.log('获取设备信息失败')
                message.error(deviceInfo.message)
            }

            //并发获取设备参数具体信息
            const res: Array<devRes | prodRes> = await Axios.all(deviceInfo.data.deviceDataList.map((item: DeviceData) => queryCategory(item.categoryID)))
            const cateArr: Array<prodRes> = res.map(element => getRes(element));
            let tmp: Array<DataParam> = []
            for (let i = 0; i < cateArr.length; i++) {
                if (!cateArr[i].isSuccessful) {
                    message.error(cateArr[i].message)
                }
                tmp[i] = (Object.assign({}, {
                    cateName: cateArr[i].data.dataCategoryName,
                    dataType: cateArr[i].data.dataType,
                    value: deviceInfo.data.deviceDataList[i].dataValue
                }))
            }
            this.setState({
                deviceData: tmp
            })
            //获取设备附件
            const attach = getRes(await queryAttachment(this.state.deviceID));
            if (!attach.isSuccessful) {
                message.error("附件获取失败" + attach.message);
            } else {
                this.setState({
                    attachments: attach.data
                })
            }

            //获取设备图片
            const pictures = getRes(await queryDevicePictures(this.state.deviceID));
            if (!pictures.isSuccessful) {
                message.error("图片获取失败" + pictures.message);
            } else {
                this.setState({
                    pictureUrls: pictures.data
                })
            }

            //获取设备3D图片
            const threeDimenRes = getRes(await queryDeviceStereoPicture(this.state.deviceID));
            if (!threeDimenRes.isSuccessful) {
                message.error("3D图片获取失败" + threeDimenRes.message);
            } else {
                this.setState({
                    threeDPaths: threeDimenRes.data
                })
            }

        } catch (err) {
            message.error(err.toString())
        }
    }

    render() {
        return (
            <Layout className='layout' style={{ minHeight: '100%' }}>
                <div className="frameCardWrapper">
                    <div className="flexRow">
                        <div className="leftFrameBox">
                            <Spin spinning={this.state.isLoading} size='large'>
                                <div className="deviceDisplayBox">
                                    <div className="deviceDisplayTitle">
                                        <div className="deviceDisplayName"><h1>{this.state.deviceInfo?.deviceName}</h1>
                                        </div>
                                        <div className="deviceDisplayInfo">
                                            <div className="rightInfo">
                                                设备所属厂商ID：{this.state.deviceInfo?.manufacturerID}
                                            </div>
                                            <div className="rightInfo">
                                                最后修改时间：{moment(this.state.deviceInfo?.manufacturerID ? this.state.deviceInfo?.manufacturerID : 0).format('YYYY-MM-DD')}
                                            </div>
                                        </div>
                                        <div style={{ maxHeight: '500px' }}>
                                            <Carousel effect="fade">
                                                {
                                                    this.state.pictureUrls.map((item: PictureInfo) => {
                                                        return (
                                                            <div key={item.pictureID}>
                                                                <div className="deviceCarouselWrap">
                                                                    <Image src={item.filePath} width='100%' alt="alt" />
                                                                </div>
                                                            </div>
                                                        )
                                                    })
                                                }
                                            </Carousel>
                                        </div>
                                        <div className="content">
                                            <Descriptions title="参数信息" bordered column={1}>
                                                {this.state.deviceData.filter(item => item.dataType === DataType.TEXT || item.dataType === DataType.SELECT).map(item => (
                                                    <Descriptions.Item
                                                        span={1}
                                                        label={item.cateName}
                                                        key={item.cateName}
                                                    >
                                                        {item.value}
                                                    </Descriptions.Item>
                                                ))}
                                            </Descriptions>
                                            {this.state.deviceData.filter(item => item.dataType === DataType.TWODIMENSIONAL).map(item => {
                                                return (
                                                    <LineChart dataBody={JSON.parse(item.value)} title={item.cateName} />
                                                )
                                            })}
                                        </div>
                                    </div>
                                </div>
                                <Divider orientation="left">
                                    3D图片
                                </Divider>
                                <ThreeDDisplay picturePaths={this.state.threeDPaths} />

                                <Divider orientation="left">
                                    附件列表
                                </Divider>
                                <List
                                    bordered
                                    dataSource={this.state.attachments}
                                    renderItem={item => (
                                        <List.Item>
                                            <a href={item.filePath} target="_blank" rel="noopener noreferrer">{item.fileName.split('/').pop()}</a>
                                        </List.Item>
                                    )}
                                />
                            </Spin>
                        </div>
                        <div className="rightFrameBox">
                            <RecommendedReq title={'测评文章'} recommendType={ArticleType.KNOWLEDGE} />
                        </div>
                    </div>

                </div>
            </Layout>
        )
    }
}
